package com.happy3w.ssp.schoolmatehome.service.note;

import com.happy3w.toolkits.message.MessageRecorderException;
import lombok.Getter;
import lombok.Setter;
import org.springframework.util.StringUtils;

import java.util.Set;
import java.util.function.Function;

@Getter
@Setter
public class NoteQuery {
    private QueryItem contents = new QueryItem();
    private QueryItem tags = new QueryItem();

    public static NoteQuery parse(String query) {
        NoteQuery noteQuery = new NoteQuery();
        if (query == null || query.isEmpty()) {
            return noteQuery;
        }
        String[] queryItems = query.split(" ");
        for (String queryItem : queryItems) {
            if (!StringUtils.hasText(queryItem)) {
                continue;
            }
            Function<QueryItem, Set<String>> setter;
            if (queryItem.startsWith("-")) {
                setter = QueryItem::getNot;
                queryItem = queryItem.substring(1);
            } else if (queryItem.startsWith("+")) {
                setter = QueryItem::getMust;
                queryItem = queryItem.substring(1);
            } else {
                setter = QueryItem::getMust;
            }

            String[] values = queryItem.split(":");
            QueryItem item;
            String value;
            if (values.length > 1) {
                String key = values[0];
                if ("tag".equalsIgnoreCase(key)) {
                    item = noteQuery.getTags();
                } else if ("content".equalsIgnoreCase(key)) {
                    item = noteQuery.getContents();
                } else {
                    throw new MessageRecorderException("不支持的条件:" + key);
                }
                value = values[1];
            } else {
                item = noteQuery.getContents();
                value = queryItem;
            }
            setter.apply(item).add(value);
        }
        return noteQuery;
    }

}
